import {request} from '../../request/request';
// async
import regeneratorRuntime from '../../utils/regenerator-runtime/runtime.js'
// pages/details/details.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    detailsObj:{},
    autoplay:true,
    indicatorDots:true,
    circular:true,
    isCollect:false
  },
  // 定义商品列表
  goodsInfo:{},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   console.log(options);
   const {goods_id} = options;
   this.shopDetails(goods_id);
  },
  async shopDetails(goods_id){
    let res = await request({url:"/goods/detail",data:{goods_id}});
    this.goodsInfo = res.data.message;
    console.log(this.goodsInfo)
    // 获取缓存中的收藏数据
    let collect = wx.getStorageSync('collect')||[];
// 判断商品有没有被收藏
  let isCollect = collect.some(v=>v.goods_id===this.goodsInfo.goods_id)
    this.setData({
      detailsObj:{
        goods_name:res.data.message.goods_name,
        pics:res.data.message.pics,
        goods_price:res.data.message.goods_price,
        goods_introduce:res.data.message.goods_introduce.replace(/\.webp/g,'.jpg'),
      },
      isCollect
    })
  },
  //预览图片
  previewImg(e){
  let urls = this.goodsInfo.data.message.pics.map(v=>v.pics_mid);
  let current = e.currentTarget.dataset.urls;
  console.log('点击预览')
  wx.previewImage({
    current, // 当前显示图片的http链接
    urls // 需要预览的图片http链接列表
  })
  },
  // 加入购物车
  addShoping(){
    // 获取缓存中购物车 数组
    var cart = wx.getStorageSync("cart") || [];
    // 判断 商品是否存在于购物车数组中
    console.log(this.goodsInfo)
    console.log(cart)
    let index = cart.findIndex(v=>v.goods_id === this.goodsInfo.goods_id)
    // console.log(this.goodsInfo.good_id)
    if(index == -1){
      // 不存在，第一次添加
      this.goodsInfo.num = 1;
      this.goodsInfo.checked=true;
      cart.push(this.goodsInfo)
    }else{
      // 已经存在数据在购物车，num++
      cart[index].num++;
    };
    wx.setStorageSync('cart', cart);
    wx.showToast({
      title: '添加成功',
      icon: 'success',
      mask:true,
      duration: 2000
    })
    // 把购物车重新添加到缓存中
    wx.setStorageSync('cart', cart)
  },
  handCollect(){
    // 默认未收藏
    let isCollect = false;
    //1.获取缓存数据
    let collect = wx.getStorageSync('collect')||[];
    // 2.判断商品有没有被收藏
    let index = collect.findIndex(v=>v.goods_id===this.goodsInfo.goods_id);
    console.log(index)
    // 当index!==-1，被收藏
    if(index !== -1){
       collect.splice(index,1);
        // 取消收藏
        isCollect = false
       wx.showToast({
        title: '取消成功',
        icon: 'success',
        mask: true
      });
    }else{
        // 3.没有收藏过
        collect.push(this.goodsInfo)
        // 添加收藏
        isCollect = true;
        wx.showToast({
          title: '收藏成功',
          icon: 'success',
          mask: true
        });
      }
      // 4.把数组存入缓存中
      wx.setStorageSync("collect", collect);
      // 5.修改data中的数据
      this.setData({
        isCollect
      })
      console.log(isCollect)
  }
})